package org.speedy.classpath;

import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Gets all tests from classpath. Uses testFilter to decide if class is a test.
 */
public class ClasspathInterogator {

	private Set<String> classes;
	private final String testFilter;

	/**
	 * Gets all tests from classpath. Uses testFilter to decide if class is a test.
	 * 
	 * @param testFilter
	 */
	public ClasspathInterogator(String testFilter) {
		this.testFilter = testFilter;
		this.classes = new HashSet<String>();
	}

	public Collection<String> findTests() {
		String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator);
		for (String entry : classPath) {
			processEntry(entry);
		}
		return classes;
	}

    private void processEntry(String entry) {
        File entryFile = new File(entry);
        if (!entryFile.exists() || !entryFile.canRead()) {
            throw new RuntimeException("cannot read class path entry: " + entryFile);
        }
        if (entryFile.isDirectory()) {
            processDirectory(entryFile, entryFile);
        } else if (entryFile.isFile()) {
        	//TODO I don't need to process jars... yet?
//            processJarFile(entryFile);
        }
    }

    private void processDirectory(File root, File dir) {
        File[] files = dir.listFiles();
		for (File f : files) {
            if (f.isDirectory()) {
                processDirectory(root, f);
            } else {
                if (f.getName().endsWith(".class")) {
                    //subtract the local filesystem gunk from the entry
                    //and remove .class at the end
                    String target = f.getAbsolutePath()
                        .substring(root.getAbsolutePath().length())
                        .replace(".class", "");

                    //in case the OS directory separator is still hanging on
                    //the front, get rid of it
                    if (target.startsWith(File.separator)) target =
                        target.substring(File.separator.length());

                    //switch the OS-specific separator to the one java expects
                    target = target.replace(File.separator, "/");

                    //add to our list of target classes
                    if (target.matches(this.testFilter)) {
                    	classes.add(target);
                    }
                }
            }
        }
    }
}
